package crm8000.Controllers

import crm8000.services.PermissionService;
import crm8000.services.UserService
import grails.converters.JSON

class PermissionController {

	static allowedMethods = [roleList: 'POST', editRole: 'POST', selectPermission: 'POST', selectUsers: 'POST',
		deleteRole: 'POST']

	PermissionService permissionService

	UserService userService

	def index() {
		if (!permissionService.hasPermission('-8996')) {
			redirect controller: 'home'
		}

		[loginUserName: userService.loginUserName]
	}

	def roleList() {
		def data = permissionService.roleList()

		render(contentType: "application/json") {
			array {
				for (r in data) {
					role id: r.id, name: r.name
				}
			}
		}
	}

	def permissionList() {
		def data = permissionService.permissionList(params.roleId)

		render(contentType: "application/json") {
			array {
				for (p in data) {
					permission id: p.id, name: p.name
				}
			}
		}
	}

	def userList() {
		def data = permissionService.userList(params.roleId)

		render(contentType: "application/json") {
			array {
				for (u in data) {
					user id: u.id, name: u.name, loginName: u.loginName, orgFullName: u.org.fullName
				}
			}
		}
	}

	def editRole() {
		def result = permissionService.editRole(params)

		render result as JSON
	}

	def selectPermission() {
		def data = permissionService.selectPermission(params)

		render(contentType: "application/json") {
			array {
				for (p in data) {
					permission id: p.id, name: p.name
				}
			}
		}
	}

	def selectUsers() {
		def data = permissionService.selectUsers(params)

		render(contentType: "application/json") {
			array {
				for (u in data) {
					user  id: u.id, name: u.name, loginName: u.loginName, orgFullName: u.org.fullName
				}
			}
		}
	}
	
	def deleteRole() {
		def result = permissionService.deleteRole(params.id) 
		
		render result as JSON 
	}
}
